package com.szholly.pro.watergas_server.ps.android.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.szholly.plug.form.core.interceptor.FormEditInterceptorClass;
import org.apache.commons.lang3.ObjectUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.service.DomainService;
import com.szholly.pro.watergas_server.ps.service.OperationDataVaildService;
import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.utils.util.JSONUtils;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.common.util.ConvertCaptionUtils;
import com.szholly.data.common.util.JSONConvertUtils;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.ITable;
import com.szholly.data.general.ITableFactory;
import com.szholly.data.general.RowBase;
import com.szholly.data.general.interceptor.DbEditType;

import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;

@Service
public class CommonAndroidService {
	private String token = "android_token";
	@Autowired
	OperationDataVaildService operationDataVaildService;
	@Autowired
	DomainService domainService;
	/**
	 * 登录接口
	 * @param userName
	 * @param password
	 * @return
	 * @throws Exception
	 */
	public String login(String userName, String password) {
		checkToken(token);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select t1.C_USERNAME,t1.C_USEREALNAME,t3.GROUP_NAME,t1.PHOTO,t1.s_userid,t3.guid as group_id  from safe_user "
				+ "t1 left join OC_GROUP_ASSO t2 on t1.s_userid=t2.user_id "
				+ "left join OC_GROUP t3 on t2.group_id=t3.guid where 1=1 ";
		if (userName != null && !userName.equals("")) {
			sql += " and t1.c_username =@userName";
			parms.add(new GlobalParameter("userName", userName));
		}
		if (password != null && !password.equals("")) {
			sql += " and t1.C_PWD =@password";
			parms.add(new GlobalParameter("password", password));
		}
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		JSONObject jo = new JSONObject();
		if (rows != null && rows.size() > 0) {
			String uid = rows.get(0).getValue("C_USERNAME").toString();
			String uname = rows.get(0).getValue("C_USEREALNAME").toString();
			String GROUP_NAME = "";
			if (rows.get(0).getValue("GROUP_NAME") != null) {
				GROUP_NAME = rows.get(0).getValue("GROUP_NAME").toString();
			}
			String GROUP_ID = "";
			if (rows.get(0).getValue("GROUP_ID") != null) {
				GROUP_ID = rows.get(0).getValue("GROUP_ID").toString();
			}
			String S_USERID = rows.get(0).getValue("S_USERID").toString();

			String pic = "";
			if (rows.get(0).getValue("PHOTO") != null) {
				pic = rows.get(0).getValue("PHOTO").toString();
			}
			jo.put("UserName", uname);
			jo.put("UserID", uid);
			jo.put("GroupName", GROUP_NAME);
			jo.put("pic", pic);
			jo.put("S_USERID", S_USERID);
			jo.put("GROUP_ID", GROUP_ID);
		} else {
			jo.put("UserName", "");
			jo.put("UserID", "");
			jo.put("GroupName", "");
			jo.put("pic", "");
			jo.put("S_USERID", "");
			jo.put("GROUP_ID", "");
		}
		// initUserRole(rows.get(0));
		return JSONUtils.toJSONString(jo);
	}
	/**
	 * 获取所有运维类型(包括污水厂、供水、地表水、工业污染)
	 * 
	 * @param userID
	 * @param type
	 * @return
	 */
	public String getAllTaskType(String userID, String type, String groupID) {
		checkToken(token);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "";
		if (groupID != null && !groupID.equals("")) {
			sql = "select count(t.exp_no) as allnum,'0' as station_category,'污水处理厂' as name　from (select t1.exp_no from BC_ENTERPRISE_ATTR t1 left join BC_SITE_INFO t2 on t2.wwtp_id=t1.exp_no "
					+ " left join OPERATION_GROUP_STATION_ASSO t3 on t2.exp_no=t3.station_id left join OC_GROUP t4 on t3.operation_group_id=t4.guid  where  t2.station_category='0' and t2.BUILD_STATUS='0' and t4.guid='"
					+ groupID + "' group by t1.exp_no)t union all "
					+ " select count(t.exp_no) as allnum,'1' as station_category,'地表水' as name　"
					+ " from (select t1.exp_no from  monitor_station t1  "
					+ "left join OPERATION_GROUP_STATION_ASSO t3 on t1.exp_no=t3.station_id "
					+ "left join OC_GROUP t4 on t3.operation_group_id=t4.guid  "
					+ "where t1.station_category='1' and t1.BUILD_STATUS='0' and t4.guid='" + groupID
					+ "' group by t1.exp_no)t union all "
					+ " select count(t.exp_no) as allnum,'2' as station_category,'工业污染' as name　"
					+ "from (select t1.exp_no from  monitor_station t1  "
					+ "left join OPERATION_GROUP_STATION_ASSO t3 on t1.exp_no=t3.station_id "
					+ "left join OC_GROUP t4 on t3.operation_group_id=t4.guid  "
					+ "where t1.station_category='2' and t1.BUILD_STATUS='0' and t4.guid='" + groupID
					+ "' group by t1.exp_no)t union all "
					+ " select count(t.exp_no) as allnum,'3' as station_category,'供水' as name　"
					+ "from (select t1.exp_no from  monitor_station t1  "
					+ "left join OPERATION_GROUP_STATION_ASSO t3 on t1.exp_no=t3.station_id "
					+ "left join OC_GROUP t4 on t3.operation_group_id=t4.guid  "
					+ "where t1.station_category='3' and t1.BUILD_STATUS='0' and t4.guid='" + groupID
					+ "' group by t1.exp_no)t  ";

			/*
			 * +
			 * " select count(t1.exp_no) as allnum,'1' as station_category,'地表水' as name from BC_SITE_INFO t1 where t1.station_category='1' and t1.BUILD_STATUS='0' union all"
			 * +
			 * " select count(t1.exp_no) as allnum,'2' as station_category,'工业污染' as name from BC_SITE_INFO t1 where t1.station_category='2' union all"
			 * +
			 * " select count(t1.exp_no) as allnum,'3' as station_category,'供水' as name from BC_SITE_INFO t1 where t1.station_category='3' "
			 * ;
			 */
		} else {
			sql = "select count(t1.exp_no) as allnum,'0' as station_category,'污水处理厂' as name　from BC_ENTERPRISE_ATTR t1 where t1.poll_type='0'  union all"
					+ " select count(t1.exp_no) as allnum,'1' as station_category,'地表水' as name from BC_SITE_INFO t1 where t1.station_category='1' and t1.BUILD_STATUS='0' union all"
					+ " select count(t1.exp_no) as allnum,'2' as station_category,'工业污染' as name from BC_SITE_INFO t1 where t1.station_category='2' union all"
					+ " select count(t1.exp_no) as allnum,'3' as station_category,'供水' as name from BC_SITE_INFO t1 where t1.station_category='3' and t1.build_status = '0' ";
		}

		/*
		 * if (userID != null && !userID.equals("")) { sql+=
		 * " and t6.c_username =@userID"; parms.add(new
		 * GlobalParameter("userID",userID) ); } if(type != null &&
		 * !type.equals("")){ //角色类型 }
		 */
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "";
		}
	}
	/**
	 * 获取是否签到信息
	 * @return
	 */
	public String getSignIn(String userId, String scId,String type){
		checkToken(token);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		JSONObject jsonObject = new JSONObject();
		String sql = null;
		if(!checkNull(type)){
			if(type.equals("0")){
				sql = "select * from OP_REGI_INFO  where to_char(time,'yyyy-MM-dd') = to_char(sysdate,'yyyy-MM-dd')";
			}else{
				sql = "select * from OP_REGI_INFO  where to_char(time,'yyyy-MM-dd') = to_char(sysdate,'yyyy-MM-dd')";
			}			
		}else{
			jsonObject.put("RESULT", "false");
			return jsonObject.toString();
		}
		if(!checkNull(userId) && !checkNull(scId)){
			sql += " and user_id = @userId and wttp_id = @scId ";
			parms.add(new GlobalParameter("userId", userId));
			parms.add(new GlobalParameter("scId", scId));
		}
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() > 0) {
			jsonObject.put("RESULT", "true");
			return jsonObject.toString();
		} else {
			jsonObject.put("RESULT", "false");
			return jsonObject.toString();
		}
	}
	/**
	 * 获取参数单位
	 * @param token
	 */
	public String getUnits(String type){
		checkToken(token);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = null;
		JSONArray jsonArray = new JSONArray();
		if(!checkNull(type)){
			if(type.equals("0")){
				sql = "select t.S_DOMAINCODE,t.S_DOMAINCAPTION,t.s_unit from data_defulatdomain t where t.S_DOMAINNAME = 'MONITOR_PARAM'";
			}else if(type.equals("1")){
				sql = "select t.S_DOMAINCODE,t.S_DOMAINCAPTION,t.s_unit from data_defulatdomain t where t.S_DOMAINNAME = 'MONITOR_PARAM'";
			}else if(type.equals("2")){
				sql = "select t.S_DOMAINCODE,t.S_DOMAINCAPTION,t.s_unit from data_defulatdomain t where t.S_DOMAINNAME = 'MONITOR_PARAM'";
			}else if(type.equals("3")){
				sql = "select t.S_DOMAINCODE,t.S_DOMAINCAPTION,t.s_unit from data_defulatdomain t where t.S_DOMAINNAME = 'MONITOR_PARAM'";
			}else{
				return jsonArray.toString();
			}
		}
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return jsonArray.toString();
		}
	}
	/**
	 * 生成任务
	 * 
	 * @param row
	 * @return
	 */
	public String generateTask(String row) {
		JSONObject json = JSONObject.fromObject(row);
		String stationId = json.get("STATION_ID").toString();
		String groupId = json.get("OPERATION_GROUP_ID").toString();
		String jobId = json.get("JOB_ID").toString();
		String pcode = json.get("TASK_CODE").toString();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd hh:mm:ss");
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = sf.format(new Date());
		String st = sfd.format(new Date());
		try {
			Object taskCountStr = DataUtil.getScale(
					" SELECT TASK_COUNT FROM OP_SITE_TASK_COUNT WHERE STATION_ID = '" + stationId + "' ",
					null);
			int taskCount = 0;
			if (taskCountStr != null) {
				taskCount = Integer.parseInt(taskCountStr + "");
			}
			String taskCode = dateStr + "-" + stationId + "-" + taskCount;
			json.put("TASK_CODE", taskCode);
			json.put("START_TIME", st);
			json.put("END_TIME", st);
			List<GlobalParameter> parms = new ArrayList<>();
			parms.add(new GlobalParameter("stationId", stationId));
			parms.add(new GlobalParameter("groupId", groupId));
			parms.add(new GlobalParameter("taskCode", taskCode));
			parms.add(new GlobalParameter("jobId", jobId));
			parms.add(new GlobalParameter("pcode", pcode));
			/*
			 * parms.add(new GlobalParameter("START_TIME", st)); parms.add(new
			 * GlobalParameter("END_TIME", st));
			 */
			String insertSql = " insert into operation_task (GUID, STATION_ID,OPERATION_GROUP_ID, TASK_STATUS, START_TIME, END_TIME, FINISH_TIME, FINISH_BY, CREATE_TIME, TASK_CODE, JOB_ID,PARENT_TASK_CODE) "
					+ "values (sys_guid(), @stationId,@groupId, '0', sysdate,sysdate, null, '', sysdate, @taskCode,@jobId,@pcode)";
			DataUtil.ExecuteUpdateSql(insertSql, parms);
		} catch (Exception e) {
			throw e;
		}
		return json.toString();
		// HashMap<String, String> map=
	}
	

	/**
	 * 数据保存
	 * 
	 * @param token
	 * @param userID
	 * @param tableName
	 * @param row
	 * @return
	 * @throws Exception
	 */
	public String save(String token, String userID, String tableName, String row, String dataType, String TASK_CODE,
			String CREATE_TIME, String FINISH_BY) throws Exception {

		checkToken(token);

		tableName = tableName.toUpperCase();
		if (tableName.equals("OP_ALAR_PROC")) {
			try {

				JSONObject json = JSONObject.fromObject(row);
				String result = json.optString("PROCESS_RESULT");
				json.put("STATUS", result);
				row = json.toString();
			} catch (Exception e) {

			}
		}
		// 设备故障及维修
		if (tableName.equals("OP_FAILURE_REPAIR") && dataType.equals("0")) {
			operationDataVaildService.IsRepair(row);
		}
		String result = null;
		try {
			RowBase entity = JSONConvertUtils.convertToEntity(row);
			Object obj = entity.getValue("_IS_DOMAIN_TRUE");
			if (obj != null && obj.toString().toLowerCase().equals("true")) {
				result = null;
			} else {
				result = tableSave(tableName, entity);
				if (!TASK_CODE.isEmpty() && !TASK_CODE.equals("")) {
					updateTaskStatus(TASK_CODE, "1", CREATE_TIME, FINISH_BY);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return result;
	}
	private String tableSave(String tableName, RowBase entity) throws Exception {
		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory.getBean("TableFactory");
		ITable pTable = tableFactory.openTable(tableName);

		String returnString = FormEditInterceptorClass.BeforeDbEditOptionEx(pTable, entity, DbEditType.Insert);
		if (StringUtils.IsNullOrSpace(returnString)) {
			pTable.startEditing();
			try {
				pTable.save(entity);

				// 再做一次字典转议
				ConvertCaptionUtils.convertCaptionField(pTable, entity);
				ObjectMapper mapper = new ObjectMapper();
				String userMapJson = mapper.writeValueAsString(entity);
				pTable.stopEditing(true);

				return userMapJson;
			} catch (Exception e) {
				pTable.stopEditing(false);
				throw e;
			}
		} else {
			return returnString;
		}
	}
	/**
	 * 更新任务状态 wangl
	 * 
	 * @param TASK_CODE
	 * @param TASK_STATUS
	 * @param CREATE_TIME
	 * @return
	 */
	public String updateTaskStatus(String TASK_CODE, String TASK_STATUS, String CREATE_TIME, String FINISH_BY) {
		String sql = "update  OPERATION_TASK set task_status='1',CREATE_TIME=to_date('" + CREATE_TIME
				+ "','yyyy-mm-dd hh24:mi:ss'),FINISH_TIME=to_date('" + CREATE_TIME + "','yyyy-mm-dd hh24:mi:ss')"
				+ ",FINISH_BY='" + FINISH_BY + "'" + " where task_code='" + TASK_CODE + "' ";
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		int i = DataUtil.ExecuteUpdateSql(sql, parms);
		if (i == 0) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}

	}
	/**
	 * 获取定期维护运维项
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */

	public String getDqwhItems(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		String result = domainService.getPeriodMaintainanceItems();
		return (result);
	}
	/**
	 * 批量数据保存
	 * 
	 * @param tableName
	 *            数据表名
	 * @param rows
	 *            记录集，Json格式数组
	 */
	public String saveList(String tableName, String rows, String dataType, String TASK_CODE, String CREATE_TIME,
			String FINISH_BY) {
		if (StringUtils.IsNullOrSpace(tableName) || StringUtils.IsNullOrSpace(rows)) {
			return null;
		}
		tableName = tableName.toUpperCase();
		// dataType站点类型：0-污染源 1-地表水 2-工业污染源 3-供水
		// 日常巡检数据
		if (tableName.equals("OP_RECO_RPT") && dataType.equals("0")) {
			operationDataVaildService.IsInspection(rows);
		}
		// 定期维护
		if (tableName.equals("OPERATION_RECORD_MAINTAINANCE") && dataType.equals("0")) {
			operationDataVaildService.IsMaintainance(rows);
		}
		// 耗材及备件更换
		if (tableName.equals("OP_MATE_REPLACE") && dataType.equals("0")) {
			operationDataVaildService.IsReplace(rows);
		}
		// 日常校准
		if (tableName.equals("OPERATION_DAILY_VERIFICATION") && dataType.equals("0")) {
			operationDataVaildService.IsVerification(rows);
		}
		// 超标比对
		if (tableName.equals("OP_EXCEED_COMP") && dataType.equals("0")) {
			operationDataVaildService.IsComparison(rows);
		}
		// 水样比对
		if (tableName.equals("OP_SAMPLE_COMP") && dataType.equals("0")) {
			operationDataVaildService.IsSampleComparison(rows);
		}
		// 标样核查
		if (tableName.equals("OP_STAND_VERI") && dataType.equals("0")) {
			operationDataVaildService.IsStandVerification(rows);
		}
		String result = null;
		List<RowBase> rowList = new ArrayList<RowBase>();
		// 数据对象
		JSONArray jsonArray = JSONArray.fromObject(rows);
		if (jsonArray.size() > 0) {
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject rowItem = jsonArray.getJSONObject(i);
				RowBase entity = (RowBase) JSONObject.toBean(rowItem, RowBase.class);
				if (!(rowItem.get("childValues") instanceof JSONNull)) {
					JSONObject childValuesObj = JSONObject.fromObject(rowItem.get("childValues"));
					getDataSource(childValuesObj, entity);
				}
				rowList.add(entity);
			}
		}
		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory.getBean("TableFactory");
		ITable pTable = tableFactory.openTable(tableName);
		String returnString = FormEditInterceptorClass.BeforeDbEditOptionEx(pTable, rowList, DbEditType.Insert);
		if (StringUtils.IsNullOrSpace(returnString)) {
			pTable.startEditing();
			try {
				pTable.save(rowList);

				pTable.stopEditing(true);
				result = "{\"result\":true}";
				updateTaskStatus(TASK_CODE, "1", CREATE_TIME, FINISH_BY);
			} catch (Exception e) {
				pTable.stopEditing(false);
				throw e;
			}
		} else {
			result = returnString;
		}
		return result;
	}
	/**
	 * 递归取子表
	 * 
	 * @param objs
	 * @param rowBase
	 * @return
	 */
	private RowBase getDataSource(JSONObject objs, RowBase rowBase) {
		JSONObject childValues = objs;
		Set<String> childTables = childValues.keySet();
		// 收集子表记录
		HashMap<String, List<RowBase>> childHashMap = new HashMap<String, List<RowBase>>();
		for (String chidlTable : childTables) {
			List<RowBase> childRowBases = new ArrayList<RowBase>();
			JSONArray list2 = (JSONArray) childValues.get(chidlTable);
			for (int i = 0; i < list2.size(); i++) {
				JSONObject jo = (JSONObject) list2.get(i);
				RowBase childRowBase = (RowBase) JSONObject.toBean(jo, RowBase.class);
				if (childRowBase.containsKey("childValues")) {
					childRowBase.remove("childValues");
				}

				// 递归取子表
				if (!(jo.get("childValues") instanceof JSONNull)) {
					JSONObject childValuesObj = JSONObject.fromObject(jo.get("childValues"));
					getDataSource(childValuesObj, childRowBase);
				}
				childRowBases.add(childRowBase);
			}
			childHashMap.put(chidlTable, childRowBases);
		}
		rowBase.setChildValues(childHashMap);
		return rowBase;
	}
	/**
	 * 获取运维组人员信息
	 * 
	 * @param exp_no
	 * @return
	 */
	public String getGroupUser(String exp_no) {
		String sql = "select t3.group_name, t3.guid, t1.s_userid, t1.c_userealname\n" + "  from safe_user t1\n"
				+ "  left join OC_GROUP_ASSO t2 on t1.s_userid = t2.user_id\n"
				+ "  left join OC_GROUP t3 on t2.group_id = t3.guid\n"
				+ " left join operation_group_station_asso t4 on t3.guid=t4.operation_group_id "
				+ " where group_name is not null";
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		if (exp_no != null && !exp_no.equals("")) {
			sql += " and t4.station_id =@exp_no";
			parms.add(new GlobalParameter("exp_no", exp_no));
		}
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "";
		}
	}
	/**
	 * android获取参数单位
	 * 
	 * @param userName
	 * @return
	 * @throws Exception
	 */
	public String getUnit() {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select t.S_DOMAINCODE,t.S_DOMAINCAPTION,t.s_unit from data_defulatdomain t where t.S_DOMAINNAME = 'MONITOR_PARAM'";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "[]";
		}
	}
	/**
	 * 获取字典值 wangl
	 * 
	 * @param S_DOMAINNAME
	 * @return
	 */

	public String getDataDefulatdomain(String S_DOMAINNAME) {
		String sql = "select S_DOMAINCODE,S_DOMAINNAME,s_domaincaption,PY_PREFIX from DATA_DEFULATDOMAIN where 1=1 and  S_DOMAINNAME is not null   ";// and
																																						// s_ischild='1'
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		if (S_DOMAINNAME != null && !S_DOMAINNAME.equals("")) {
			sql += " and S_DOMAINNAME =@S_DOMAINNAME";
			parms.add(new GlobalParameter("S_DOMAINNAME", S_DOMAINNAME));
		}
		sql += " order by i_order";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		// List<HashMap<String, HashMap<String,String>>> allData = new
		// ArrayList<>();
		List<JSONObject> allData = new ArrayList<>();
		if (rows != null && rows.size() >= 0) {
			for (int i = 0; i < rows.size(); i++) {
				// HashMap<String,HashMap<String,String>> temp=new
				// HashMap<String,HashMap<String,String>>();
				// HashMap<String,Object> temp=new HashMap<String,Object>();
				JSONObject temp = new JSONObject();
				HashMap<String, String> map = new HashMap<String, String>();
				HashMap<String, Object> dmoin = rows.get(i);
				String str = dmoin.get("S_DOMAINNAME").toString();
				for (int j = 0; j < dmoin.size(); j++) {
					// for(int j=0;j<rows.size();j++){
					HashMap<String, Object> dmoinc = rows.get(j);
					if (dmoinc.get("S_DOMAINNAME").toString().equals(str)) {
						map.put(dmoinc.get("S_DOMAINCODE").toString(), dmoinc.get("S_DOMAINCAPTION").toString());
						temp.put(dmoinc.get("S_DOMAINNAME").toString(), map);
					}
				}
				allData.add(temp);
			}
			String result = JSONUtils.toJSONString(allData);
			return result;
		} else {
			return "";
		}
	}
	// 获取版本号
	public String getVersionNo() {
		List<GlobalParameter> parms = new ArrayList();
		String sql = "select * from ANDROID_VERSION_CONFIG";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "";
		}
	}
	/**
	 * 删除创建未完成的任务
	 * 
	 *
	 */
	@RequestMapping("/delUndoneGenerate")
	@ResponseBody
	public String delUndoneGenerate(String TASK_CODE) throws Exception {
		if (TASK_CODE.isEmpty()) {
			return "{\"result\":false}";
		}
		List<GlobalParameter> parms = new ArrayList();
		String Sql = "delete from OP_TASK t where t.TASK_STATUS = '0' and t.TASK_CODE = @TASK_CODE";
		parms.add(new GlobalParameter("TASK_CODE", TASK_CODE));
		int i = DataUtil.ExecuteUpdateSql(Sql, parms);
		if (i == 0) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}
	}
	public String getOperationTaskNum(String factoryId,String type){
		if(checkNull(factoryId)){
			return "[]";
		}
		List<GlobalParameter> parms = new ArrayList();
		String sql = null;
		if(type.equals("0")){
			sql = "select count(t.station_id) as totalnum,  t.job_id,t1.flow_type,Translate(t.station_id USING NCHAR_CS) as station_id from OP_TASK t  "
					+ "left join BC_SITE_INFO t1 on t.station_id = t1.exp_no where TASK_STATUS = '0'  "
					+ "and t1.WWTP_ID = @factoryId  group by t.job_id,t1.flow_type,t.station_id union all "
					+ "select count(t3.wwtp_id) as totalnum,'123456' as job_id, Translate(t3.flow_type USING NCHAR_CS) as flow_type ,t2.station_code as station_id from OP_ALAR_INFO t2 "
					+ "left join BC_SITE_INFO t3 on t2.station_code = t3.exp_no "
					+ "where t3.wwtp_id = @factoryId and t2.STATUS = '0'and is_recover = '0'  group by t3.flow_type,t3.wwtp_id,t2.station_code ";
		}else if(type.equals("1")){
			sql = "select count(t.station_id) as totalnum,  t.job_id,t1.flow_type,Translate(t.station_id USING NCHAR_CS) as station_id from OP_TASK t  "
					+ "left join BC_SITE_INFO t1 on t.station_id = t1.exp_no where TASK_STATUS = '0'  "
					+ "and t1.exp_no = @factoryId  group by t.job_id,t1.flow_type,t.station_id union all "
					+ "select count(t3.wwtp_id) as totalnum,'123456' as job_id, Translate(t3.flow_type USING NCHAR_CS) as flow_type ,t2.station_code as station_id from OP_ALAR_INFO t2 "
					+ "left join BC_SITE_INFO t3 on t2.station_code = t3.exp_no "
					+ "where t3.exp_no = @factoryId and t2.STATUS = '0'and is_recover = '0'  group by t3.flow_type,t3.wwtp_id,t2.station_code ";
		}
		 
		parms.add(new GlobalParameter("factoryId", factoryId));
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "[]";
		}
	}
	public String getTaskList(String jobId,String stationId){
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		// 所有任务语句
		String sql = "select  t1.task_code,t1.task_status,t2.name as station_name,t1.job_id,to_char"
				+ "(t1.start_time,'yyyy-mm-dd hh24:mi:ss') as start_time ,to_char(t1.end_time,'yyyy-mm-dd hh24:mi:ss')"
				+ " as end_time , to_char(t1.FINISH_TIME,'yyyy-mm-dd hh24:mi:ss') as FINISH_TIME,t1.station_id from"
				+ "  Operation_Task t1 left join BC_SITE_INFO t2 on t1.station_id = t2.exp_no  where 1 = 1  ";
		if(!checkNull(jobId) && !checkNull(stationId) ){
			sql += " and t1.job_id = @jobId";
			sql += " and t1.station_id = @stationId";
			parms.add(new GlobalParameter("jobId", jobId));
			parms.add(new GlobalParameter("stationId", stationId));
		}
		List<RowBase> rowProcessed = DataUtil.getSelectRows(sql, parms);
		JSONArray ProcessedData = new JSONArray();
		JSONArray PendingData = new JSONArray();
		if (rowProcessed != null && rowProcessed.size() > 0) {
			for (int i = 0; i < rowProcessed.size(); i++) {
				HashMap<String, Object> d = rowProcessed.get(i);
				String task_status = d.get("TASK_STATUS").toString();
				Calendar deathCal = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String et = d.get("END_TIME").toString();// 截止时间
				// String st=d.get("START_TIME").toString();//开始时间
				Date et_date = new Date();
				// Date st_date=new Date();
				Date fishtime_date = new Date();
				Date nowdate = new Date();
				try {
					et_date = sdf.parse(et);
					// st_date=sdf.parse(st);
					deathCal.setTime(et_date);
				} catch (ParseException e) {

					e.printStackTrace();
				}
//				int timeCycleNum = Integer.parseInt(d.get("TASK_TOLERANCE").toString().replaceAll("[a-zA-Z]", ""));
//				if (d.get("TASK_TOLERANCE").toString().indexOf("D") > 0) {
//					deathCal.add(Calendar.DAY_OF_MONTH, timeCycleNum);
//				} else if (d.get("TASK_TOLERANCE").toString().indexOf("M") > 0) {
//					deathCal.add(Calendar.MONTH, timeCycleNum);
//				}
//				Date truefishtime = deathCal.getTime();

				if (task_status.equals("0")) {// 未处理
					// if (truefishtime.getTime() >= nowdate.getTime()) {
					PendingData.add(d);
					// } else {
					// TimeoutHandlingData.add(d);
					// }
				}
				if (task_status.equals("1")) {// 已处理
					String fishtime = d.get("FINISH_TIME").toString();// 完成时间
					try {
						fishtime_date = sdf.parse(fishtime);
					} catch (ParseException e) {

						e.printStackTrace();
					}
					ProcessedData.add(d);
					// 暂时屏蔽，不做超时判断
					/*
					 * if(fishtime_date.getTime()>=truefishtime.getTime()){
					 * ProcessedData.add(d); } else{ TimeoutHandlingData.add(d);
					 * }
					 */
				}
			}
		}
		JSONObject jsobj = new JSONObject();
		jsobj.put("PendingData", PendingData);
		jsobj.put("ProcessedData", ProcessedData);
		List<JSONObject> allData = new ArrayList<>();
		allData.add(jsobj);
		String result = JSONUtils.toJSONString(allData);
		return JSONUtils.toJSONString(result);
	}
	public String getAbnormalDisposalData(String jobId, String station_id) {
		checkToken(token);
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();

		String sql = "select * from (select t1.guid, t1.type,t1.alarm_value,t1.station_code,t1.status,'a' as fish_type,to_char((t1.createtime+1),'yyyy-mm-dd hh24:mi:ss')  "
				+ "as END_TIME,to_char((t1.createtime),'yyyy-mm-dd hh24:mi:ss')  as START_TIME,'123456' as job_id,d1.s_domaincaption as type_desc "
				+ "from OP_ALAR_INFO t1 " + "left join BC_SITE_INFO t2  on t1.station_code = t2.exp_no  "
				+ "left join DATA_DEFULATDOMAIN d1 on ( d1.S_DOMAINNAME = '报警类型' AND d1.S_DOMAINCODE = t1.type )\n"
				+ "where  t1.status = '0' and t1.is_recover='0' and t1.station_code='" + station_id
				+ "' order by t1.start_time desc)t  \n" + "union all\n"
				+ "select * from (select t1.guid, t1.type,t1.alarm_value,t1.station_code,t1.status,'b' as fish_type,to_char((t1.createtime+1),'yyyy-mm-dd')  as END_TIME"
				+ ",to_char((t1.createtime),'yyyy-mm-dd')  as START_TIME,'123456' as job_id,d1.s_domaincaption as type_desc"
				+ " from OP_ALAR_INFO t1 " + "left join BC_SITE_INFO t2  on t1.station_code = t2.exp_no"
				+ " left join DATA_DEFULATDOMAIN d1 on ( d1.S_DOMAINNAME = '报警类型' AND d1.S_DOMAINCODE = t1.type )\n"
				+ "left join OP_ALAR_PROC t3 on t1.guid=t3.alarm_id\n"
				+ "where  t1.status = '1' and (t3.end_time-t1.createtime)  < 1 and t1.station_code='" + station_id
				+ "' and t1.updatetime >= trunc(sysdate ,'MM') AND t1.updatetime <= last_day(sysdate) order by t1.start_time desc)t \n" + "union all\n"
				+ "select * from (select t1.guid, t1.type,t1.alarm_value,t1.station_code,t1.status,'c' as fish_type,to_char((t1.createtime+1),'yyyy-mm-dd')  as END_TIME,to_char((t1.createtime),'yyyy-mm-dd')  as START_TIME,'123456' as job_id,d1.s_domaincaption as type_desc from OP_ALAR_INFO t1 left join BC_SITE_INFO t2  on t1.station_code = t2.exp_no left join DATA_DEFULATDOMAIN d1 on ( d1.S_DOMAINNAME = '报警类型' AND d1.S_DOMAINCODE = t1.type )\n"
				+ "left join OP_ALAR_PROC t3 on t1.guid=t3.alarm_id\n"
				+ "where  t1.status = '1' and (t3.end_time-t1.createtime)  >1 and t1.station_code='" + station_id
				+ "' and t1.updatetime >= trunc(sysdate ,'MM') AND t1.updatetime <= last_day(sysdate) order by t1.start_time desc)t ";
		//筛选当月数据
//				sql += " and  t1.start_time >= trunc(sysdate ,'MM') AND t1.start_time <= last_day(sysdate) ";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		JSONArray ProcessedData = new JSONArray();// 正常时间已处理
		JSONArray PendingData = new JSONArray();// 待处理
		if (rows != null && rows.size() > 0) {
			for (int i = 0; i < rows.size(); i++) {
				HashMap<String, Object> d = rows.get(i);
				String FISH_TYPE = d.get("FISH_TYPE").toString();
				if (FISH_TYPE.equals("a")) {// 待处理
					PendingData.add(d);
				}
				if (FISH_TYPE.equals("b")) {// 已处理
					ProcessedData.add(d);
				}
				if(FISH_TYPE.equals("c")){//原来超时处理的现在没有这个概念，结果加进已处理
					ProcessedData.add(d);
				}
			}
			JSONObject jsobj = new JSONObject();
			jsobj.put("PendingData", PendingData);
			jsobj.put("ProcessedData", ProcessedData);
			List<JSONObject> allData = new ArrayList<>();
			allData.add(jsobj);
			String result = JSONUtils.toJSONString(allData);
			return JSONUtils.toJSONString(result);
		} else {
			return null;
		}
	}
	private void checkToken(String token) {
		if (!ObjectUtils.equals(token, this.token)) {
			throw new RuntimeException("认证错误！");
		}
	}
	static boolean checkNull(String date){
		if(null == date || date.isEmpty()){
			return true;
		}else{
			return false;
		}
	}
}
